package net.toocruel.iqismart.web.aop;

import net.toocruel.iqismart.entity.setting.Setting;
import net.toocruel.iqismart.service.SettingService;
import net.toocruel.iqismart.service.exception.UpdateSettingException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/5/7 下午2:55
 */
@Aspect
@Component
public class SettingControllerAop {
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    @Autowired
    private SettingService settingService;

    @Pointcut("execution(* net.toocruel.iqismart.web.controller.admin.AdminSettingController.*(..))")
    public void executeSettingController(){

    }

    @Around("executeSettingController()")
    public Object arround(ProceedingJoinPoint pjp) {
        Object o = null;
        try {
            o =  pjp.proceed();
//            Arrays.stream(pjp.getArgs()).forEach(arg->{
//                if(arg instanceof BindingResult){
//                    BindingResult bindingResult = (BindingResult) arg;
//                    if(bindingResult.hasErrors()){
//                        throw new UpdateSettingException();
//                    }
//                }
//            });
            //更新配置信息
            if (thymeleafViewResolver != null) {
                Map<String, Object> vars = new HashMap<>();
                Setting setting = settingService.getSetting();
//                Setting.SETTING = setting;
                BeanUtils.copyProperties(setting,Setting.SETTING);
                vars.put("GlobalSetting", setting);
                thymeleafViewResolver.setStaticVariables(vars);
            }
        } catch (UpdateSettingException e){
            //do nothing
        }catch (Throwable e) {
            e.printStackTrace();
        }
        return o;
    }

}


